package com.example.java.base.rabbitmq.a4direct;

import com.example.java.base.rabbitmq.util.RabbitMqUtil;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * Consumer:消费消息
 *
 * @author zhangxiaoxiang
 * @date 2020/11/15
 */
public class Consumer2 {
    public static void main(String[] args) {
        String exchangeName="logs_direct";
        try {
            // 获取connection
            Connection connection = RabbitMqUtil.getConnection();
            // 获取channel
            final Channel channel = connection.createChannel();
            //    绑定交换机
            channel.exchangeDeclare("logs_direct", "direct");
            //    临时队列
            String queueName = channel.queueDeclare().getQueue();
            //   基于route key绑定队列和交换机
            channel.queueBind(queueName, exchangeName, "info");
            channel.queueBind(queueName, exchangeName, "error");
            channel.queueBind(queueName, exchangeName, "warning");
            //    消费消息
            channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("消费者2: " + new String(body));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}